import React, { Component } from 'react'
import { Card,Breadcrumb,Form,Button,Input,Radio,Upload,Modal,message} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import { Link } from 'react-router-dom'
import {Channel} from 'components/Channel/Channel'
import { baseURL } from 'utils/request'

// 富文本编辑器
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css';
// 样式
import styles from './articlepublish.module.scss'
import { addArticle,editArticle,getArticleContent } from 'api/article'
// import { upload } from 'api/uploadimg'

export class ArticlePublis extends Component {
  state = {
    type:0,
    fileList:[],
    showPreview:false,
    previewImageUrl:'',
    editId:this.props.match.params.id
  }
  formRef = React.createRef()
  async componentDidMount(){
    if(this.state.editId) {
      const res = await getArticleContent(this.state.editId)
      // console.log(res)
      const images = res.data.cover.images.map(item => {
        return {url:item}
      })
      const values = {
        ...res.data,
        type:res.data.cover.type
      }
      this.formRef.current.setFieldsValue(values)
      this.setState({
        type:res.data.cover.type,
        fileList:images
      })
    }
  }
  render() {
    console.log(this.props)
    const {type,fileList,showPreview,previewImageUrl,editId} = this.state
    return (
      <div className={styles.articlepublish}>
        <Card title={
          <Breadcrumb>
            <Breadcrumb.Item> <Link to='/home'>首页</Link> </Breadcrumb.Item>
            <Breadcrumb.Item>{editId ? '修改文章' : '文章发布'}</Breadcrumb.Item>
          </Breadcrumb> }>
          <Form labelCol={{span:4}} wrapperCol={{span:16}} ref={this.formRef} onFinish={this.pubArticleInfo} validateTrigger={['onChange','onBlur']} initialValues={{content:'',type}}>
            <Form.Item label='标题' name='title' wrapperCol={{span:8}} rules={[{required:true,message:'文章标题不能为空！'}]}>
              <Input/>
            </Form.Item>
            <Form.Item label='频道' name='channel_id' rules={[{required:true,message:'文章频道不能为空！'}]}>
              <Channel></Channel>
            </Form.Item>
            <Form.Item label='封面' name='type'>
              <Radio.Group name="radiogroup" onChange={this.cgType}>
                <Radio value={0}>无图</Radio>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{offset:4}}>
              <Upload action={baseURL+'upload'} listType="picture-card" fileList={fileList} maxCount={type} name='image' onPreview={this.showPreviewFn} beforeUpload={this.beforeUpload} onChange={this.cgImages} disabled={type === 0 ? true : false}>
                <PlusOutlined/>
              </Upload>
            </Form.Item>
            <Form.Item label='内容' name='content' rules={[{required:true,message:'文章内容不能为空！'}]}>
              <ReactQuill theme="snow"></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{offset:4}}>
              <Button type='primary' htmlType='submit' size='large'>{editId ? '修改文章' : '文章发布'}</Button>
              <Button style={{ marginLeft: 16 }} onClick={this.draftArticle} size='large'>存为草稿</Button>
            </Form.Item>
          </Form>
        </Card>
        <Modal visible={showPreview} title='封面预览' footer={null} onCancel={this.hidePreview}>
          <img alt="example" style={{ width: '100%' }} src={previewImageUrl} />
        </Modal>
      </div>
    )
  }
  async saveArticle(value,draft,info) {
    const {type,fileList,editId} = this.state
    if(fileList.length !== type) {
      return message.error('上传图片数目错误！')
    }
    // console.log(value)
    // console.log(this.state.fileList)
    const images = fileList.map((item) => item.url || item.response.data.url)
    const data = {
      ...value,
      cover:{
        type,
        images
      }
    }
    if(editId) {
      await editArticle(data,draft,editId).catch((err) => {
        message.error(`发布失败！error:${err.response.data.message}`,1)
      })
      info = '修改成功'
      message.success(info)
    } else {
      await addArticle(data,draft).catch((err) => {
        message.error(`发布失败！error:${err.response.data.message}`,1)
      })
      message.success(info)
    }
    this.props.history.push('/home/list')
  }

  pubArticleInfo = (value) => { // 文章内容
    this.saveArticle(value,false,'发布成功！')
  }

  draftArticle = async () => { // 保存草稿
    const value = await this.formRef.current.validateFields()
    this.saveArticle(value,true,'保存草稿成功！')
  }

  cgType = (e) => { // 封面数量 无图 单图 三图
    // console.log(e.target.value)
    // [].includes()
    this.setState({
      type:e.target.value,
      fileList:[]
    })
  }

  beforeUpload = (file) => {
    if(!['image/jpeg','image/jpg','image/png'].includes(file.type)){
      message.error('您只能上传 JPEG/JPG/PNG 格式的图片！');
      return Upload.LIST_IGNORE
    } 
    if(file.size >= 1024 * 500){
      message.error('图片大小不能超过 500KB !');
      return Upload.LIST_IGNORE
    }

    return true

  }

  cgImages = (cginfo) => { // Upload change方法 上传图片
    // console.log(cginfo)
    this.setState({
      fileList:cginfo.fileList
    })
  }

  showPreviewFn = (file) => { // 显示预览图片
    // console.log(file)
    const imgurl = file.url || file.response.data.url
    this.setState({
      showPreview:true,
      previewImageUrl:imgurl
    })
  }
 
  hidePreview = () => { // 隐藏预览
    this.setState({
      showPreview:false,
      previewImageUrl:''
    })
  }
}

export default ArticlePublis